package com.jacen.fzxs.manager;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jacen.fzxs.controller.LoginController;
import com.jacen.fzxs.util.StrUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 权限控制的拦截器
 * 
 * @author Jacen
 *
 */
public class BaseInterceptor implements HandlerInterceptor {

	private static Set<String> publicUrlSet;
	private static boolean RIGHT_MODEL = false;//权限控制开关

	public static final class ErrorType {
		public static final int NO_SESSION = 0;// session为空
		public static final int NO_RIGHT = 1;// 无权限访问
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		// 初始化UrlSet
		if (publicUrlSet == null) {
			publicUrlSet = new HashSet<String>();
			String urlsStr = request.getSession().getServletContext().getInitParameter("publicUrl");
			if (!StrUtils.isEmpty(urlsStr)) {
				publicUrlSet.addAll(Arrays.asList(urlsStr.split(",")));
			}
		}
		// public URL，允许直接访问
		String url = request.getServletPath();
		if (publicUrlSet.contains(url))
			return true;

		// session不存在，访问其它URL，会被转移到index.do
		if (request.getSession().getAttribute(LoginController.USERNAME) == null) {
			response.sendRedirect(request.getContextPath() + "/login.do?error=" + ErrorType.NO_SESSION);
			return false;
		} else {
			if(!RIGHT_MODEL){
				return true;
			}
			// 判断是否有权限
			@SuppressWarnings("unchecked")
			Set<String> rightSets = (Set<String>) request.getSession().getAttribute("rightMarkSession");
			if (!rightSets.contains(url)) {
				request.getSession().invalidate();
				response.sendRedirect(request.getContextPath() + "/login.do?error=" + ErrorType.NO_RIGHT+"&url="+url);
				return false;
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView)
			throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e)
			throws Exception {

	}
}
